<?php

namespace App\Http\Controllers;

use App\Http\Helper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class IndexController extends Controller
{
    //
    public function index()
    {
        if(Helper::checkLogin()) return redirect('/home');

        return view('index');
    }

    public function test()
    {
        dump(Redis::sort('newuserlink',['sort'=>'asc','get'=>'user:userid:*:username']));
    }

    /**
     * 注册功能的实现
     */
    public function register(Request $request)
    {
        Helper::checkLogin();

        $this->validate($request, [
            'username' => 'required',
            'password' => 'required',
            'password2' => 'required',
        ]);

        $res = Redis::get(Helper::getUserIdKey($request->input('username')));
        if(empty($res))
        {
            $uid = Helper::getAutoUserId();
            Redis::set(Helper::getUserKey($uid),$request->input('username')); //添加注册信息
            Redis::set(Helper::getUserPassKey($uid),$request->input('password')); //添加注册信息
            Redis::set(Helper::getUserIdKey($request->input('username')),$uid); //添加注册信息

            //这一种和下面的写法都是可以的
            Redis::lpush('newuserlink',[$uid]);
            Redis::ltrim('newuserlink',0,49);

            //Redis::command('lpush',['newuserlink',$uid]);
            //Redis::command('ltrim',['newuserlink',0,49]);
        }

        return view('register',[
            'ifRegister' => $res ? 1 : 0
        ]);
    }

    /**
     * 用户登录的相关操作
     * @param Request $request
     * @return string
     */
    public function login(Request $request)
    {
        $uid = Redis::get(Helper::getUserIdKey($request->input('username')));
        if(empty($uid)) return '用户不存在';

        $password = Redis::get(Helper::getUserPassKey($uid));
        if($password != $request->input('password'))
        {
            return '密码不正确';
        }

        $cookie = cookie('user',[
            'username' => $request->input('username'),
            'uid' => $uid
        ]);
        $secret = Helper::randSercet();
        cookie('authsecret',$secret);
        Redis::set('user:userid:'.$uid.':authsecret',$secret); //登陆后的随机验证码

        return redirect('home')->cookie($cookie);
    }

    /**
     * 退出操作
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function logout()
    {
        Redis::set('user:userid:'.Cookie::get('user')['uid'].':authsecret',''); //清空随机验证码
        return redirect('/')->withCookie(cookie('user','',-1))->withCookies('authsecret','');
    }

    /**
     * 用户中心
     * @param Request $request
     * @return $this|\Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function home(Request $request)
    {
        if(empty(Cookie::get('user'))) return redirect('/')->withErrors('你还没有登录！');

        //我关注的人
        $start = Redis::smembers('following:'.Cookie::get('user')['uid']);
        $start[] = Cookie::get('user')['uid']; //包含自己的微博信息

        //拉取的开始点
        $lastpull = Redis::get('lastpull:userid:'.Cookie::get('user')['uid']) ? Redis::get('lastpull:userid:'.Cookie::get('user')['uid']) : 0;
        //拉取数据
        $latest = [];
        foreach($start as $s)
        {
            $res = Redis::zrangebyscore('starpost:userid:'.$s,$lastpull + 1,pow(2,30));
            $latest = array_merge($latest,$res);
        }
        sort($latest,SORT_NUMERIC);
        if(!empty($latest))
        {
            Redis::set('lastpull:userid:'.Cookie::get('user')['uid'],end($latest)); //设置上一次取的值
        }

        //取出限制条目的微博
        foreach ($latest as $v)
        {
            Redis::lpush('recivepost:'.Cookie::get('user')['uid'],$v);
        }
        Redis::ltrim('recivepost:'.Cookie::get('user')['uid'],0,9999); // ltrim key 0 0 清空一下

        $data = Redis::sort('recivepost:'.Cookie::get('user')['uid'],['sort'=>'desc']);

        $res = [];
        foreach($data as $k => $v)
        {
            $res[] = Redis::hMGet('post:postid:'.$v,['userid','time','content','username']);
        }

        //获取关注和被关注的数量
        $gz = Redis::scard('following:'.Cookie::get('user')['uid']);
        $bgz = Redis::scard('follower:'.Cookie::get('user')['uid']);

        return view('home',[
            'res' => $res,
            'user' => Cookie::get('user'),
            'gz' => $gz,
            'bgz' => $bgz
        ]);
    }

    /**
     * 发布帖子
     * @param Request $request
     * @return $this
     */
    public function post(Request $request)
    {
        if(empty(Cookie::get('user'))) return redirect('/')->withErrors('你还没有登录！');

        $postId = Helper::getAutoPostId();
        $user = Cookie::get('user');
        //Redis::set('post:postid:'.$postId.':userid',$user['uid']);
        //Redis::set('post:postid:'.$postId.':time',time());
        //Redis::set('post:postid:'.$postId.':content',$request->input('status'));
        //保存成hash值方便存取
        Redis::hmset('post:postid:'.$postId,[
            'content' => $request->input('status'),
            'time' => time(),
            'userid' => $user['uid'],
            'username' => $user['username']
        ]);

        //修改为拉去模式
        Redis::zadd('starpost:userid:'.$user['uid'],$postId,$postId);
        if(Redis::zcard('starpost:userid:'.$user['uid']) > 20)
        {
            Redis::zremrangebyrank('starpost:userid:'.$user['uid'],0,0); //超过20条删除最旧的一条记录
        }

        //维护1000条用户资源数据
        Redis::lpush('mypost:userid:'.$user['uid'],$postId);
        $len = Redis::llen('mypost:userid:'.$user['uid']);
        if($len > 5)
        {
            Redis::rpoplpush('mypost:userid:'.$user['uid'],'global:store'); //数据大于1000条，那么存放到删除空间中
        }

        return redirect('home');
    }

    /**
     * 热门页面
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function timeline()
    {
        $userList = Redis::sort('newuserlink',['sort'=>'asc','get'=>'user:userid:*:username']);

        return view('timeline',[
            'userList' => $userList
        ]);
    }

    /**
     * 关注操作
     * @param Request $request
     * @param $username
     * @return $this
     */
    public function profile(Request $request,$username = '')
    {
        if(empty(Cookie::get('user'))) return redirect('/')->withErrors('你还没有登录！');
        //通过username查询出来uid
        $uid = Helper::getUserIdByName($username); //关注用户的id
        if(empty($uid)) abort('200','用户不存在');
        //判断是否已经关注这个用户了
        $ifFollow = Redis::sismember('following:'.Cookie::get('user')['uid'],$uid);

        return view('profile',[
            'ifFollow' => $ifFollow,
            'followUid' => $uid,
            'username' => $username
        ]);
    }

    //关注操作
    public function follow($uid)
    {
        if(Cookie::get('user')['uid'] == $uid) abort('200','不能关注自己');
        $username = Helper::getUserNameById($uid);

        $ifFollow = Redis::sismember('following:'.Cookie::get('user')['uid'],$uid);
        if(empty($ifFollow))
        {
            Redis::sadd('following:'.Cookie::get('user')['uid'],$uid); //添加到关注用户集合 这个用户关注了谁的集合
            Redis::sadd('follower:'.$uid,Cookie::get('user')['uid']); //添加到被关注用户集合 这个用户被谁关注了的集合
        }
        else
        {
            //取消关注
            Redis::srem('following:'.Cookie::get('user')['uid'],$uid);
            Redis::srem('follower:'.$uid,Cookie::get('user')['uid']);
        }

        return redirect('profile/'.$username);
    }

    /**
     * 登录检测的地方
     * @return bool
     */
    public function isLogin()
    {
        $login = true;
        if(empty(Cookie::get('authsecret'))) $login = false;
        if(empty(Redis::get('user:userid:'.Cookie::get('user')['uid'].':authsecret'))) $login = false;
        if((Redis::get('user:userid:'.Cookie::get('user')['uid'].':authsecret')) != Cookie::get('authsecret')) $login = false;
        if(empty(Cookie::get('user'))) $login = false;

        return $login;
    }

    public function queue()
    {
        $i = 0;
        $data = [];
        while (Redis::llen('global:store') && $i++ < 1000)
        {
            $postid = Redis::rpop('global:store');
            $post = Redis::hMGet('post:postid:'.$postid,['userid','time','content','username']);
            $data[] = [
                'id' => $postid,
                'userid' => $post[0],
                'time' => date('Y-m-d H:i:s',$post[1]),
                'content' => $post[2],
                'username' => $post[3],
            ];
        }

        DB::table('post')->insert($data);
    }

    public function mongodb()
    {
        $db = \DB::connection('mongodb')->getMongoClient();


        $user = DB::connection('mongodb')->collection('users')->get();
        DB::connection('mongodb')->collection('users')->insert(['id'=>1,'name'=>'wenqing']);
    }

    public function url()
    {
        Helper::urlTrans('65');
    }

    public function getNextSequence($name, $db)
    {
        $db = \DB::connection('mongodb')->getMongoClient();

        $ret = $db->command(array(
            "findandmodify" => "counters",
            "query" => array(
                "_id" => $name
            ),
            "update" => array(
                '$inc' => array(
                    "seq" => 1
                )
            ),
            "new" => true
        ));

        return $ret['value']['seq'];
    }
}